package com.cheer.ba.choosepic.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.cheer.ba.R;
import com.cheer.ba.choosepic.util.Bimp;
import com.cheer.ba.choosepic.util.ImageItem;
import com.cheer.ba.choosepic.util.PublicWay;
import com.cheer.ba.choosepic.zoom.PhotoView;
import com.cheer.ba.choosepic.zoom.ViewPagerFixed;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.utils.ImageUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * GalleryAty
 * Author: hq
 * Email: 834138841@qq.com
 * Comment: 用于进行图片浏览时的界面
 * Date: 2017/7/27  15:00
 */
public class GalleryAty extends BaseCommAty {

    //删除按钮
    @BindView(R.id.id_pic_del_btn)
    Button mBtnDel;
    //下载按钮
    @BindView(R.id.id_pic_down_txt)
    ImageView mImgDown;
    //图片数量
    @BindView(R.id.id_pic_num_txt)
    TextView mTxtPicNun;
    //图片中部展示
    @BindView(R.id.id_pic_look_viewpager)
    ViewPagerFixed mViewPager;
    private MyPageAdapter adapter;
    //用于存储查看图片的数据
    private ArrayList<View> listViews = null;

    //记录是否显示删除
    private boolean isDel;
    //记录图片浏览的当前位置
    private int position;

    @Override
    protected boolean isTitleBarShow() {
        return false;
    }

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.plugin_camera_gallery, null, false));
    }

    @Override
    public void initView() {
        position = getIntent().getIntExtra(IntentKey.General.KEY_POS, Constants.DEFAULTVALUE);
        isDel = getIntent().getBooleanExtra(IntentKey.General.KEY_BOOLEAN, false);
        if (isDel) {
            mBtnDel.setVisibility(View.VISIBLE);
            mImgDown.setVisibility(View.GONE);
        } else {
            mBtnDel.setVisibility(View.GONE);
            mImgDown.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initData() {
        PublicWay.num = Bimp.tempSelectBitmap.size();
        for (int i = 0; i < PublicWay.num; i++) {
            if (isDel) {
                //相册中浏览
                initListViews(Bimp.tempSelectBitmap.get(i).getBitmap());
            } else {
                //通用用于查看图片
                initListViews(Bimp.tempSelectBitmap.get(i));
            }
        }
        adapter = new MyPageAdapter(listViews);
        mViewPager.setAdapter(adapter);
        mViewPager.setPageMargin((int) getResources().getDimensionPixelOffset(R.dimen.ui_10_dip));
        mViewPager.setOnPageChangeListener(pageChangeListener);
        mViewPager.setCurrentItem(position);
        handPicNum(position);
    }

    private void initListViews(Bitmap bm) {
        if (listViews == null)
            listViews = new ArrayList<View>();
        PhotoView img = new PhotoView(this);
        img.setBackgroundColor(0xff000000);
        img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        img.setImageBitmap(bm);
        listViews.add(img);
    }

    private void initListViews(ImageItem model) {
        if (listViews == null)
            listViews = new ArrayList<View>();
        PhotoView img = new PhotoView(this);
        img.setBackgroundColor(0xff000000);
        img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        //文件状态 0 有问题 1正常
        int fileStatus = model.getFileStatus();
        String url = model.getPicUrl();
        int drawable = fileStatus == 1 ? R.drawable.ic_pl_pic_bg : R.drawable.ic_pic_error_rule;
        ImageUtils.showImg(aty, url, drawable, drawable, img);
        listViews.add(img);
    }

    /**
     * 处理下方图片定位
     */
    public void handPicNum(int location) {
        mTxtPicNun.setText((location + 1) + "/" + PublicWay.num);
    }

    private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
        public void onPageSelected(int arg0) {
            position = arg0;
            handPicNum(position);
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageScrollStateChanged(int arg0) {
        }
    };

    @OnClick({R.id.id_pic_back_txt, R.id.id_pic_del_btn, R.id.id_pic_down_txt})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_pic_back_txt:
                //返回按钮
                finish();
                break;
            case R.id.id_pic_del_btn:
                //删除图片按钮
                if (listViews.size() == 1) {
                    PublicWay.num = 0;
                    Bimp.tempSelectBitmap.clear();
                    Bimp.max = 0;
                    handPicNum(0);

                    BaseEvent event = new BaseEvent();
                    event.type = IntentKey.General.KEY_FINISH;
                    EventBus.getDefault().post(event);
                    finish();
                } else {
                    Bimp.tempSelectBitmap.remove(position);
                    PublicWay.num = Bimp.tempSelectBitmap.size();
                    Bimp.max--;
                    mViewPager.removeAllViews();
                    listViews.remove(position);
                    adapter.setListViews(listViews);
                    adapter.notifyDataSetChanged();

                    if (position == 0) {
                        handPicNum(0);
                    } else {
                        handPicNum(position - 1);
                    }

                    BaseEvent event = new BaseEvent();
                    event.type = IntentKey.General.KEY_FINISH;
                    EventBus.getDefault().post(event);
                }
                break;
            case R.id.id_pic_down_txt:
                //下载按钮
                checkPermissCamer();
                break;
        }
    }

    /**
     * 图片浏览的适配器
     */
    class MyPageAdapter extends PagerAdapter {
        private ArrayList<View> listViews;
        private int size;

        public MyPageAdapter(ArrayList<View> listViews) {
            this.listViews = listViews;
            size = listViews == null ? 0 : listViews.size();
        }

        public void setListViews(ArrayList<View> listViews) {
            this.listViews = listViews;
            size = listViews == null ? 0 : listViews.size();
        }

        public int getCount() {
            return size;
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPagerFixed) arg0).removeView(listViews.get(arg1 % size));
        }

        public void finishUpdate(View arg0) {
        }

        public Object instantiateItem(View arg0, int arg1) {
            try {
                ((ViewPagerFixed) arg0).addView(listViews.get(arg1 % size), 0);
            } catch (Exception e) {
            }
            return listViews.get(arg1 % size);
        }

        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    }


    /**
     * 检测用户是否开启权限
     */
    private void checkPermissCamer() {
        String[] perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!mayRequestPermission(perms)) {
            return;
        }
        toPhotoGraph();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            toPhotoGraph();
        }
    }

    /**
     * 下载图片
     */
    private void toPhotoGraph() {
        ToastUtil.showToast("正在下载");
        ImageItem item = Bimp.tempSelectBitmap.get(position);
        new Task().execute(item.getPicUrl());
    }

    private Bitmap bitmap;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0x123) {
                SavaImage(bitmap, Environment.getExternalStorageDirectory().getPath() + "/Cheer_APP");
            }
        }

        ;
    };

    /**
     * 异步线程下载图片
     */
    class Task extends AsyncTask<String, Integer, Void> {

        protected Void doInBackground(String... params) {
            bitmap = GetImageInputStream((String) params[0]);
            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Message message = new Message();
            message.what = 0x123;
            handler.sendMessage(message);
        }
    }

    /**
     * 获取网络图片
     *
     * @param imageurl 图片网络地址
     * @return Bitmap 返回位图
     */
    public Bitmap GetImageInputStream(String imageurl) {
        URL url;
        HttpURLConnection connection = null;
        Bitmap bitmap = null;
        try {
            url = new URL(imageurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public void SavaImage(Bitmap bitmap, String path) {
        File file = new File(path);
        FileOutputStream fileOutputStream = null;
        //文件夹不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            fileOutputStream = new FileOutputStream(path + "/" + System.currentTimeMillis() + ".jpg");
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            sendBroadcast(intent);
            ToastUtil.showToast("保存成功,文件路径" + file.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
